﻿using System;
using System.Data.Linq;
using System.Linq;
using iHouse.Infrastructure;
using iHouse.Model.Data;
using iHouse.Model.Repository.Interface;

namespace iHouse.Model.Repository
{
    public class SqlNoteRepository : BaseRepository<iHouseDbContext, Note>, INoteRepository
    {
        protected override string ContextKey
        {
            get { return "DataContextForNote"; }
        }

        protected override PaginationList<Note> GetDataByCategory(int categoryID, int pageIndex, int pageSize)
        {
            return (from i in CurrentDataContext.Notes
                    where i.CategoryID == categoryID
                    orderby i.CreatedDate
                    select i)
                    .ToPaginationList(pageIndex, pageSize);
        }

        protected override PaginationList<Note> GetData(PagingCriteria criteria)
        {
            return (from i in CurrentDataContext.Notes
                    orderby i.ID
                    select i)
                    .ToPaginationList(criteria);
        }

        #region INoteRepository

        public void CreateNote(Note note)
        {
            note.CreatedDate = DateTime.Now;
            CurrentDataContext.Notes.Add(note);
            CurrentDataContext.SaveChanges();
        }

        public void UpdateNote(int noteID, Note newNote)
        {
            Note note = this.GetNoteByID(noteID);
            note.CategoryID = newNote.CategoryID;
            note.Description = newNote.Description;
            note.Reference = newNote.Reference;
            note.Title = newNote.Title;

            CurrentDataContext.SaveChanges();
        }

        public void DeleteNote(int noteID)
        {
            Note note = CurrentDataContext.Notes.Single(x => x.ID == noteID);

            CurrentDataContext.Notes.Remove(note);
            CurrentDataContext.SaveChanges();
        }

        public Note GetNoteByID(int noteID)
        {
            return CurrentDataContext.Notes.Single(x => x.ID == noteID);
        }

        public int GetNoteCount(int categoryID)
        {
            return CurrentDataContext.Notes.Where(x => x.CategoryID == categoryID).Count();
        }

        #endregion
    }
}
